package xyz.scootaloo.mono.data

import org.ktorm.database.Database
import org.ktorm.global.connectGlobally
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.StringRedisTemplate
import xyz.scootaloo.mono.base.lang.asString
import xyz.scootaloo.mono.base.service.async.AsyncTaskService
import java.util.concurrent.TimeUnit
import javax.sql.DataSource

/**
 * 配置数据源对象
 * - ktorm [Database]
 * - redis [StringRedisTemplate]
 *
 * ### 资料参考
 * - [ktorm](https://www.ktorm.org/zh-cn/)
 * - [Spring-Starter](https://www.jianshu.com/p/bbf439c8a203)
 * - [StringRedisTemplate](https://www.cnblogs.com/slowcity/p/9002660.html)
 *
 * @author flutterdash@qq.com
 * @since 2021/7/25 15:41
 */
@Configuration
@ComponentScan(basePackages = ["xyz.scootaloo.mono.data"])
class DatabaseAutoConfiguration : ApplicationRunner {

    @Autowired lateinit var dataSource: DataSource
    @Autowired lateinit var redisTemplate: StringRedisTemplate

    @Autowired lateinit var async: AsyncTaskService

    @Bean
    fun getDatabase(): Database = Database.connectGlobally(dataSource)

    override fun run(args: ApplicationArguments?) {
        testRedisConnection()
    }

    private fun testRedisConnection() = async.schedule {
        println(redisTemplate.asString())
        val testStr = "test-connect"
        redisTemplate.opsForValue().set(
            testStr, "hello world", 3, TimeUnit.SECONDS
        )
        val receive: String? = redisTemplate.opsForValue().get(testStr)
        println(if (receive != null) "redis连接正常" else "redis连接失败")
    }

}
